
package com.akupilih.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.akupilih.app.adapter.BeritaAdapter;
import com.akupilih.app.entity.E_Berita;
import com.akupilih.app.helper.JSONHelper;
import com.akupilih.app.helper.VolleyHelper;
import com.akupilih.app.model.DBClass;
import com.akupilih.app.model.WebService;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

public class BeritaFragment extends Fragment {
    public static final String KEY_TITLE = "title";
    public static final String KEY_EXCERPT = "excerpt";
    public static final String KEY_DATE = "date";
    public static final String TAG = "Berita";
    private String URL;

    ArrayList<HashMap<String, String>> postitem;
    ListView listView;
    List<E_Berita> dataList;
    private SwipeRefreshLayout layout;
    private FragmentActivity myContext;

    public BeritaFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        URL = WebService.BERITA();
        layout = (SwipeRefreshLayout) inflater.inflate(
                R.layout.fragment_berita, container, false);
        listView = (ListView) layout.findViewById(R.id.listview);
        DBClass db = new DBClass(getActivity());
        dataList = db.getBerita();
        setList(dataList);
        return layout;
    }

    protected void goToDetailBerita(int position) {
        postitem = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("title", dataList.get(position).getTitle());
        map.put("author", dataList.get(position).getAuthor());
        map.put("date", dataList.get(position).getDate());
        map.put("content", dataList.get(position).getContent());
        map.put("url", dataList.get(position).getUrl());
        postitem.add(map);
        Intent i = new Intent(getActivity(), BeritaDetailActivity.class);
        i.putExtra("berita", postitem);
        startActivity(i);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        layout.setColorScheme(R.color.red, R.color.orange, R.color.yellow,
                R.color.maroon);
        layout.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                layout.setRefreshing(true);
                Log.e(getClass().getSimpleName(), "refresh");
                getBerita(myContext, URL);
                setList(dataList);

            }
        });
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                goToDetailBerita(position);
            }
        });

    }

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        myContext = (FragmentActivity) activity;

    }

    private void setList(List<E_Berita> dataList2) {
        postitem = new ArrayList<HashMap<String, String>>();
        if (dataList2 != null) {
            for (E_Berita e : dataList2) {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(KEY_TITLE, e.getTitle());
                map.put(KEY_DATE, e.getDate());
                map.put(KEY_EXCERPT, e.getExcerpt());
                postitem.add(map);
            }
            BeritaAdapter adapter = new BeritaAdapter(myContext, postitem);
            listView.setAdapter(adapter);
            listView.setDivider(null);
            adapter.notifyDataSetChanged();
        }

    }

    public void getBerita(final Context contex, String URL) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
                URL, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject obj) {

                        try {
                            JSONArray root = obj.getJSONArray("posts");
                            JSONHelper.getBerita(root, contex);
                            layout.setRefreshing(false);
                        } catch (JSONException e) {
                            ACRAPostSender.TRACE(TAG + " ERROR", "getData : "
                                    + e.getMessage());
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO Auto-generated method stub
                        ACRAPostSender.TRACE(TAG
                                + ".getData(...).new ErrorListener() {...}",
                                "onErrorResponse : " + error.toString());
                        VolleyHelper.showVolleyError(contex, error);
                    }
                });
        BaseApplication.getInstance().addToRequestQueue(request, TAG);
    }
}
